package jcu.salt.client;

import java.rmi.RemoteException;

import jcu.sal.common.Constants;
import jcu.sal.common.agents.SALAgent;
import jcu.sal.common.agents.SALAgentFactory;
import jcu.sal.common.events.ClientEventHandler;
import jcu.sal.common.events.Event;
import jcu.sal.common.exceptions.ConfigurationException;
import jcu.sal.common.exceptions.NotFoundException;

/** 
 * This is more or less a stripped version cloned by the rmi client of the
 * SAL project: COPIED CODE!!!!
 * 
 * It is made abstract to focus in the more specialized {@link SaltRmiClient} more
 * on the glue code between turbine and SAL. 
 * 
 * TODO: should be moved to SAL project because most parts are out of SAL-T's scope
 * 
 * @author SAL-T team
 *
 */

public abstract class RmiClient implements ClientEventHandler{
	
	protected SALAgent agent;
	
	
	public RmiClient(String rmiName, String agentRMIRegIP, String ourIP) throws RemoteException {
		try {
			agent = SALAgentFactory.getFactory().createRMIAgent(agentRMIRegIP, ourIP, rmiName);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RemoteException();
		}
	}
	
	
	public void start(String ourRmiIP) throws ConfigurationException{
		try {
			agent.registerEventHandler(this, Constants.SENSOR_MANAGER_PRODUCER_ID);
			agent.registerEventHandler(this, Constants.PROTOCOL_MANAGER_PRODUCER_ID);
			agent.registerEventHandler(this, Constants.SENSOR_STATE_PRODUCER_ID);
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public abstract void run();
		
	public void stop() throws RemoteException {
		try {
			agent.unregisterEventHandler(this, Constants.SENSOR_MANAGER_PRODUCER_ID);
			agent.unregisterEventHandler(this, Constants.PROTOCOL_MANAGER_PRODUCER_ID);
			agent.unregisterEventHandler(this, Constants.SENSOR_STATE_PRODUCER_ID);
		} catch (NotFoundException e) {
			//cant unregister our event handler, keep going
		}		
	}
	
	public void release() throws RemoteException{
		SALAgentFactory.getFactory().releaseRMIAgent(agent);
	}

	public void handle(Event e, SALAgent a) {
		System.out.println("Received "+e.toString()+ " from "+agent.getID());
	}
}

